package com.liu.qqclient.Service;

import com.liu.qqcommon.Message;
import com.liu.qqcommon.MessageType;
import com.liu.qqcommon.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 该类完成用户登录验证和用户注册等功能
 */
public class UserClientService {
    private User u = new User();
    private Socket socket;
    //根据 userId 和 pwd 到服务端是否有效
    public boolean checkUser(String userId, String pwd)  {
        boolean b = false;
        u.setUserId(userId);
        u.setPassword(pwd);

        //连接到服务端，发送u对象
        try {
            socket = new Socket(InetAddress.getByName("192.168.56.1"), 9999);
            //发送对象
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(u);//发送User对象


            //读取从服务端传入的对象
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            Message ms = (Message) ois.readObject();

            if(ms.getMesType().equals(MessageType.MESSAGE_LOGIN_SUCCEED)){
                //创建一个和服务端保持通讯的线程，——>创建一个类ClientConnectServerThread
                ClientConnectServerThread clientConnectServerThread = new ClientConnectServerThread(socket);
                //启动客户端线程
                clientConnectServerThread.start();
                //为了后面客户端的扩展，将线程放入集合管理
                ManageClientConnectServerThread.addClientConnectServerThread(userId,clientConnectServerThread);
                b = true;
            }else {
                //如果登录失败，就不能启动和服务端通讯的线程，需要关闭socket
                socket.close();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return b;
    }
    //向服务器端请求在线人数
    public void onlineFriendList() {
        //发送一个Message，类型是MESSAGE_GET_ONLINE_FRIEND
        Message message = new Message();
        message.setMesType(MessageType.MESSAGE_GET_ONLINE_FRIEND);
        message.setSender(u.getUserId());
        //发送给服务器
        //应当得到当前的Socket 对应的ObjectOutputStream对象
        try {
            ObjectOutputStream oos = new ObjectOutputStream(ManageClientConnectServerThread.getClientConnectServerThread(u.getUserId()).getSocket().getOutputStream());
            oos.writeObject(message);
        } catch (IOException e) {
           e.printStackTrace();
        }
    }
    //向服务端请求关闭通讯
    public void offlineFriendList() {
        Message message = new Message();
        message.setMesType(MessageType.MESSAGE_CLIENT_EXIT );
        message.setSender(u.getUserId());
        try {
            ObjectOutputStream oos = new ObjectOutputStream(ManageClientConnectServerThread.getClientConnectServerThread(u.getUserId()).getSocket().getOutputStream());
            oos.writeObject(message);
            System.out.println( u.getUserId()+"退出系统");
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
